import { HUOBI_SUBSCRIBE_MARKET_SYMBOLS } from "./constants";
import { utilTransferCoinTypeToUpperCase } from "./marketUtil";
import { IReduxMarketItem } from "../interface";

// const WebSocket = require('isomorphic-ws');
const pako = require('pako');

const WS_URL = 'wss://api.huobi.pro/ws';

type marketWSCallback = (err: Error | null, data: any) => void;

interface IMarketData {
    id: number,
    open: number,
    close: number,
    low: number,
    high: number,
    amount: number,
    vol: number,
    count: number,
}

var orderbook = {};


function handleMarketData (symbol:string, data: IMarketData): IReduxMarketItem | null {
    let coinType = utilTransferCoinTypeToUpperCase(symbol);
    const {open, close, low, high, amount} = data;
    // console.log('data....', data);
    if (coinType) {
        let extent = ((close - open) / open * 100).toFixed(2) + '%';
        return {
            type: coinType,
            extent,
            value: close,
            lastPrice: close,
            low,
            high,
            amount,
        }
    }
    return null;
}


function handle(data, cb: marketWSCallback) {
    // console.log('received', data.ch, 'data.ts', data.ts, 'crawler.ts', moment().format('x'));
    let symbol = data.ch.split('.')[1];
    let channel = data.ch.split('.')[2];
    switch (channel) {
        case 'depth':
            orderbook[symbol] = data.tick;
            break;
        case 'kline':
            cb(null, handleMarketData(symbol, data.tick));
            break;
    }
}

function subscribe(ws) {
    // var symbols = ['ethbtc', 'eosbtc'];
    // 订阅深度
    // 谨慎选择合并的深度，ws每次推送全量的深度数据，若未能及时处理容易引起消息堆积并且引发行情延时
    
    // for (let symbol of symbols) {
    //     ws.send(JSON.stringify({
    //         "sub": `market.${symbol}.depth.step5`,
    //         "id": `${symbol}`
    //     }));
    // }
    // 订阅K线
    for (let symbol of HUOBI_SUBSCRIBE_MARKET_SYMBOLS) {
        ws.send(JSON.stringify({
            "sub": `market.${symbol}.kline.1day`,
            "id": `${symbol}`
        }));
    }
}

var ws;

function init(cb: marketWSCallback) {
    if (!ws) {
        console.log('init...');
    }
    ws = new WebSocket(WS_URL);
    
    ws.onopen = () => {
        console.log('open');
        subscribe(ws);
    };
    ws.onmessage = (e) => {
        let data = e.data;
        let text = pako.inflate(data, {
            to: 'string'
        });
        let msg = JSON.parse(text);
        if (msg.ping) {
            ws.send(JSON.stringify({
                pong: msg.ping
            }));
        } else if (msg.tick) {
            handle(msg, cb);
        } else {
            console.log(text);
        }
    } 
    ws.onclose =  () => {
        console.log('close');
        init(cb);
    };

    ws.onerror = (err) => {
        console.log('error', err);
        // init(cb);
        setTimeout(init(cb), 10000);
    };
}



function initMarketWS (cb: marketWSCallback) {
    console.log('marketSocket....., init', cb);
    init(cb);
}

export {
    initMarketWS
}